package org.example.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectResult;
import lombok.extern.slf4j.Slf4j;
import org.example.config.OSSConfig;
import org.example.service.FileService;
import org.example.util.CommonUtil;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * @description:
 * @author: 谢超
 * @date: 2023/7/25 13:25
 */
@Service
@Slf4j
public class FileServiceImpl implements FileService {

    @Resource
    private OSSConfig ossConfig;

    @Override
    public String uploadUserImg(MultipartFile file) {
        String bucketName = ossConfig.getBucketname();
        String endpoint = ossConfig.getEndpoint();
        String accessKeyId = ossConfig.getAccessKeyId();
        String accessKeySecret = ossConfig.getAccessKeySecret();

        // oss客户端构建
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        // 获取文件原始名称 xxx.jpg
        String originalFilename = file.getOriginalFilename();

        // 获取日期格式
        LocalDateTime now = LocalDateTime.now();
        DateTimeFormatter pattern = DateTimeFormatter.ofPattern("yyyy/MM/dd");

        // 文件名称拼接
        String folder = pattern.format(now);
        String fileName = CommonUtil.generateUUID();

        // 截取文件格式.前缀
        String extendsion = originalFilename.substring(originalFilename.lastIndexOf("."));

        // 在oss上的bucket创建文件夹
        String dirFileName = "user/" + folder + "/" + fileName + extendsion;
        try {
            PutObjectResult putObjectResult = ossClient.putObject(bucketName, dirFileName, file.getInputStream());

            // 拼装返回路径
            if (putObjectResult != null) {
                String imgURL = "https://" + bucketName + "." + endpoint + "/" + dirFileName;
                return imgURL;
            }
        } catch (IOException e) {
            log.info("文件上传失败:{}", e.getMessage());
        } finally {
            ossClient.shutdown();
        }
        return null;
    }
}
